#!/usr/bin/env python3
"""
lcy. 代码仓库初始化与 README 管理工具

一个自动化脚本，用于：
1. 克隆指定的git仓库
2. 自动添加README.md文件
3. 执行git add/commit/push操作
4. 重命名默认分支为main

使用方法:
    python init_repo.py <仓库URL> [选项]

示例:
    python init_repo.py https://gitcode.com/user/repo.git
    python init_repo.py https://gitcode.com/user/repo.git --message "初始化项目" --branch main
"""

import subprocess
import sys
import os
import argparse
from pathlib import Path
import re


class GitRepoInitializer:
    """Git仓库初始化工具类"""
    
    def __init__(self, repo_url, commit_message="add README", branch_name="main"):
        self.repo_url = repo_url
        self.commit_message = commit_message
        self.branch_name = branch_name
        self.repo_name = self._extract_repo_name()
        
    def _extract_repo_name(self):
        """从URL中提取仓库名称"""
        # 处理各种格式的URL
        match = re.search(r'/([^/]+?)(?:\.git)?/?$', self.repo_url)
        if match:
            return match.group(1)
        else:
            return "repo"
    
    def run_command(self, command, cwd=None):
        """执行shell命令并返回结果"""
        try:
            result = subprocess.run(
                command, 
                shell=True, 
                cwd=cwd,
                capture_output=True, 
                text=True,
                check=True
            )
            return True, result.stdout.strip()
        except subprocess.CalledProcessError as e:
            return False, e.stderr.strip()
    
    def check_git_installed(self):
        """检查git是否已安装"""
        success, _ = self.run_command("git --version")
        if not success:
            print("❌ 错误: Git未安装或未配置到PATH中")
            return False
        return True
    
    def clone_repository(self):
        """克隆仓库"""
        if os.path.exists(self.repo_name):
            print(f"⚠️  目录 '{self.repo_name}' 已存在，跳过克隆步骤")
            return True
        
        print(f"📥 正在克隆仓库: {self.repo_url}")
        success, output = self.run_command(f"git clone {self.repo_url}")
        
        if success:
            print(f"✅ 克隆成功")
            return True
        else:
            print(f"❌ 克隆失败: {output}")
            return False
    
    def add_readme(self):
        """添加README.md文件"""
        readme_path = Path(self.repo_name) / "README.md"
        
        # 如果README已存在，则追加内容
        if readme_path.exists():
            print("📄 README.md 已存在，追加内容")
            with open(readme_path, 'a', encoding='utf-8') as f:
                f.write(f"\n# {self.repo_name}\n")
        else:
            print("📄 创建 README.md")
            with open(readme_path, 'w', encoding='utf-8') as f:
                f.write(f"# {self.repo_name}\n\n")
                f.write("## 项目简介\n\n")
                f.write("这是一个自动初始化的项目。\n\n")
                f.write("## 快速开始\n\n")
                f.write("```bash\n")
                f.write("# 克隆项目\ngit clone <repository-url>\n\n")
                f.write("# 进入目录\ncd {}\n".format(self.repo_name))
                f.write("```\n")
        
        return True
    
    def git_operations(self):
        """执行git操作：add, commit, branch rename, push"""
        repo_path = Path(self.repo_name)
        
        # 检查是否是git仓库
        if not (repo_path / ".git").exists():
            print("❌ 错误: 这不是一个git仓库")
            return False
        
        print("🔄 执行git操作...")
        
        # 1. git add
        success, _ = self.run_command("git add README.md", cwd=repo_path)
        if not success:
            print("❌ git add 失败")
            return False
        
        # 2. git commit
        commit_cmd = f'git commit -m "{self.commit_message}"'
        success, output = self.run_command(commit_cmd, cwd=repo_path)
        if not success:
            # 可能没有变化
            if "nothing to commit" in output.lower():
                print("⚠️  没有需要提交的更改")
            else:
                print(f"❌ git commit 失败: {output}")
                return False
        
        # 3. 检查当前分支
        success, current_branch = self.run_command("git rev-parse --abbrev-ref HEAD", cwd=repo_path)
        if not success:
            print("❌ 无法获取当前分支")
            return False
        
        # 4. 重命名分支（如果需要）
        if current_branch != self.branch_name:
            print(f"🔄 重命名分支: {current_branch} -> {self.branch_name}")
            rename_cmd = f"git branch -m {self.branch_name}"
            success, _ = self.run_command(rename_cmd, cwd=repo_path)
            if not success:
                print("❌ 分支重命名失败")
                return False
        
        # 5. git push
        print("🚀 推送到远程仓库...")
        push_cmd = f"git push -u origin {self.branch_name}"
        success, output = self.run_command(push_cmd, cwd=repo_path)
        if success:
            print("✅ 推送成功")
            return True
        else:
            # 可能是首次推送需要设置上游
            if "set-upstream" in output.lower():
                print("⚠️  首次推送，设置上游分支...")
                success, _ = self.run_command(push_cmd, cwd=repo_path)
                if success:
                    print("✅ 推送成功")
                    return True
            print(f"❌ 推送失败: {output}")
            return False
    
    def run(self):
        """运行完整的初始化流程"""
        print("🚀 开始初始化仓库...")
        print("=" * 50)
        
        # 检查git
        if not self.check_git_installed():
            return False
        
        # 克隆仓库
        if not self.clone_repository():
            return False
        
        # 添加README
        if not self.add_readme():
            return False
        
        # 执行git操作
        if not self.git_operations():
            return False
        
        print("=" * 50)
        print("🎉 仓库初始化完成！")
        print(f"📁 本地路径: ./{self.repo_name}")
        print(f"🔗 远程仓库: {self.repo_url}")
        print(f"🌿 默认分支: {self.branch_name}")
        
        return True


def main():
    """主函数"""
    parser = argparse.ArgumentParser(
        description="lcy. 代码仓库初始化与 README 管理工具",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  python init_repo.py https://gitcode.com/user/repo.git
  python init_repo.py https://gitcode.com/user/repo.git --message "初始化项目"
  python init_repo.py https://gitcode.com/user/repo.git --branch develop
        """
    )
    
    parser.add_argument("repo_url", help="Git仓库URL")
    parser.add_argument("-m", "--message", default="add README", 
                       help="提交信息 (默认: 'add README')")
    parser.add_argument("-b", "--branch", default="main", 
                       help="默认分支名 (默认: 'main')")
    
    args = parser.parse_args()
    
    # 创建初始化器并运行
    initializer = GitRepoInitializer(
        repo_url=args.repo_url,
        commit_message=args.message,
        branch_name=args.branch
    )
    
    success = initializer.run()
    sys.exit(0 if success else 1)


if __name__ == "__main__":
    main()
